package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.article.mapper.ApArticleConfigMapper;
import com.heima.article.mapper.ApArticleContentMapper;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.ApArticleService;
import com.heima.common.constants.ArticleConstants;
import com.heima.common.constants.BehaviorConstants;
import com.heima.common.redis.CacheService;
import com.heima.model.article.dtos.ArticleCommentDto;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.article.dtos.ArticleHomeDto;
import com.heima.model.article.dtos.ArticleInfoDto;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApArticleConfig;
import com.heima.model.article.pojos.ApArticleContent;
import com.heima.model.article.vo.ArticleCommnetVo;
import com.heima.model.article.vo.HotArticleVo;
import com.heima.model.article.vo.StatisticsVo;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.mess.ArticleVisitStreamMess;
import com.heima.model.user.pojo.ApUser;
import com.heima.model.wemedia.dtos.StatisticsDto;
import com.heima.utils.common.DateUtils;
import com.heima.utils.thread.AppThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 文章信息表，存储已发布的文章 服务实现类
 * </p>
 *
 * @author itheima
 */
@Slf4j
@Service
@Transactional
public class ApArticleServiceImpl extends ServiceImpl<ApArticleMapper, ApArticle> implements ApArticleService {

    @Autowired
    private ApArticleMapper apArticleMapper;

    private static final Short PAGE_MAX_SIZE = 50;

    /**
     * 加载文章列表
     *
     * @param type
     * @param dto
     * @return
     */
    @Override
    public ResponseResult load(Short type, ArticleHomeDto dto) {
        //为了增加代码的容错性和健壮性，建议做一些非空判断

        //分页条数
        Integer size = dto.getSize();
        if (size == null || size == 0) {
            size = 10;
        }
        size = Math.min(size, PAGE_MAX_SIZE);
        dto.setSize(size);

        //频道
        if (StringUtils.isBlank(dto.getTag())) {
            dto.setTag(ArticleConstants.DEFAULT_TAG);
        }

        //时间判断
        if (dto.getMaxBehotTime() == null) dto.setMaxBehotTime(new Date());
        if (dto.getMinBehotTime() == null) dto.setMinBehotTime(new Date());

        List<ApArticle> articleList = apArticleMapper.loadArticleList(type, dto);
        return ResponseResult.okResult(articleList);
    }

    /**
     * 加载文章首页
     *
     * @param type
     * @param dto
     * @param firstPage 是否是首页
     * @return
     */
    @Override
    public ResponseResult loadV2(Short type, ArticleHomeDto dto, boolean firstPage) {
        if (firstPage) {
            String articleList_json = cacheService.get(ArticleConstants.HOT_ARTICLE_FIRST_PAGE + dto.getTag());
            if (StringUtils.isNotBlank(articleList_json)) {
                List<HotArticleVo> hotArticleVos = JSON.parseArray(articleList_json, HotArticleVo.class);
                return ResponseResult.okResult(hotArticleVos);
            }
        }
        return load(type, dto);
    }

    @Autowired
    private ApArticleConfigMapper apArticleConfigMapper;

    @Autowired
    private ApArticleContentMapper apArticleContentMapper;

    /**
     * 保存app端相关文章（feign）
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult saveAppArticle(ArticleDto dto) {

       /* try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
*/

        //1.检验参数
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //属性拷贝
        ApArticle apArticle = new ApArticle();
        BeanUtils.copyProperties(dto, apArticle);

        //2.判断是否存在id
        if (dto.getId() == null) {
            //2.1 不存在id,保存ap_article，ap_article_config,ap_article_content

            save(apArticle);

            ApArticleConfig apArticleConfig = new ApArticleConfig(apArticle.getId());
            apArticleConfigMapper.insert(apArticleConfig);

            ApArticleContent apArticleContent = new ApArticleContent();
            apArticleContent.setArticleId(apArticle.getId());
            apArticleContent.setContent(dto.getContent());
            apArticleContentMapper.insert(apArticleContent);

        } else {
            //2.2 存在id   修改ap_article，ap_article_content
            updateById(apArticle);
            //修改文章内容
            ApArticleContent apArticleContent = apArticleContentMapper.selectOne(Wrappers.<ApArticleContent>lambdaQuery().eq(ApArticleContent::getArticleId, apArticle.getId()));
            apArticleContent.setContent(dto.getContent());
            apArticleContentMapper.updateById(apArticleContent);
        }


        //3.结果返回，需要返回的是ap_article中的id
        return ResponseResult.okResult(apArticle.getId());
    }

    @Autowired
    private CacheService cacheService;

    @Override
    public ResponseResult loadArticleBehavior(ArticleInfoDto dto) {

        //0.检查参数
        if (dto == null || dto.getArticleId() == null || dto.getAuthorId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //{ "isfollow": true, "islike": true,"isunlike": false,"iscollection": true }
        boolean isfollow = false, islike = false, isunlike = false, iscollection = false;

        ApUser user = AppThreadLocalUtil.getUser();
        if (user != null) {
            //喜欢行为
            String likeBehaviorJson = (String) cacheService.hGet(BehaviorConstants.LIKE_BEHAVIOR + user.getId().toString(), dto.getArticleId().toString());
            if (org.apache.commons.lang3.StringUtils.isNotBlank(likeBehaviorJson)) {
                islike = true;
            }
            //不喜欢的行为
            String unLikeBehaviorJson = (String) cacheService.hGet(BehaviorConstants.UN_LIKE_BEHAVIOR + user.getId().toString(), dto.getArticleId().toString());
            if (org.apache.commons.lang3.StringUtils.isNotBlank(unLikeBehaviorJson)) {
                isunlike = true;
            }
            //是否收藏
            String collctionJson = (String) cacheService.hGet(BehaviorConstants.COLLECTION_BEHAVIOR + user.getId(), dto.getArticleId().toString());
            if (org.apache.commons.lang3.StringUtils.isNotBlank(collctionJson)) {
                iscollection = true;
            }

            //是否关注
            Double score = cacheService.zScore(BehaviorConstants.APUSER_FOLLOW_RELATION + user.getId(), dto.getAuthorId().toString());
            System.out.println(score);
            if (score != null) {
                isfollow = true;
            }

        }

        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("isfollow", isfollow);
        resultMap.put("islike", islike);
        resultMap.put("isunlike", isunlike);
        resultMap.put("iscollection", iscollection);

        return ResponseResult.okResult(resultMap);
    }

    /**
     * 图文统计统计
     *
     * @param wmUserId
     * @param beginDateStr
     * @param endDateStr
     * @return
     */
    @Override
    public ResponseResult queryLikesAndConllections(Integer wmUserId, String beginDateStr, String endDateStr) {

        Date beginDate = DateUtils.stringToDate(beginDateStr);
        Date endDate = DateUtils.stringToDate(endDateStr);

        StatisticsVo statisticsVo = apArticleMapper.queryLikesAndConllections(wmUserId, beginDate, endDate);
        return ResponseResult.okResult(statisticsVo);
    }

    /**
     * 分页查询 图文统计
     *
     * @param dto
     * @return
     */
    @Override
    public PageResponseResult newPage(StatisticsDto dto) {

        //类型转换
        dto.setStartDate(DateUtils.stringToDate(dto.getBeginDate()));
        dto.setLastDate(DateUtils.stringToDate(dto.getEndDate()));

        //暂存当前页
        Integer currentPage = dto.getPage();
        dto.setPage((dto.getPage() - 1) * dto.getSize());
        //分页查询
        List<ApArticle> apArticleList = apArticleMapper.queryArticlePageByWmuser(dto);
        int count = apArticleMapper.queryArticleCountByWmuser(dto);

        PageResponseResult responseResult = new PageResponseResult(currentPage, dto.getSize(), count);
        responseResult.setData(apArticleList);

        return responseResult;
    }

    /**
     * 查询文章评论统计
     *
     * @param dto
     * @return
     */
    @Override
    public PageResponseResult findNewsComments(ArticleCommentDto dto) {

        //暂存当前页
        Integer currentPage = dto.getPage();
        dto.setPage((dto.getPage() - 1) * dto.getSize());
        //分页查询
        List<ArticleCommnetVo> list = apArticleMapper.findNewsComments(dto);
        int count = apArticleMapper.findNewsCommentsCount(dto);

        PageResponseResult responseResult = new PageResponseResult(currentPage, dto.getSize(), count);
        responseResult.setData(list);
        return responseResult;
    }

    /**
     * 更新数据库的点赞量等，更新redis中的分值
     *
     * @param mess
     */
    @Override
    public void updateScore(ArticleVisitStreamMess mess) {

        //1.更新数据库的行为数量
        ApArticle apArticle = updateArticle(mess);

        //2.计算分值（权重当日最高  整体 * 3）
        Integer score = computeScore(apArticle);
        score = score * 3;


        //3.获取当前文章所在频道的缓存数据
        replaceDataToRedis(ArticleConstants.HOT_ARTICLE_FIRST_PAGE + apArticle.getChannelId(), apArticle, score);


        //4.获取当前推荐频道的缓存数据
        replaceDataToRedis(ArticleConstants.HOT_ARTICLE_FIRST_PAGE + ArticleConstants.DEFAULT_TAG, apArticle, score);


    }

    /**
     * 获取缓存数据并替换
     * @param key
     * @param apArticle
     * @param score
     */
    private void replaceDataToRedis(String key, ApArticle apArticle, Integer score) {
        String articleList_all_json = cacheService.get(key);
        if(StringUtils.isNotBlank(articleList_all_json)){
            List<HotArticleVo> hotArticleVos = JSON.parseArray(articleList_all_json, HotArticleVo.class);
            //3.1 假如这个文章在缓存中存在，更新文章的分值，重新排名
            boolean flag = false;
            for (HotArticleVo hotArticleVo : hotArticleVos) {
                if(hotArticleVo.getId().equals(apArticle.getId())){
                    hotArticleVo.setScore(score);
                    flag = true;
                    break;
                }
            }

            if(!flag){
                if(hotArticleVos.size() >=30){
                    //3.2 假如这个文章在缓存中不存在，比较缓存中分值最小的文章
                    HotArticleVo lastHot = hotArticleVos.get(hotArticleVos.size() - 1);
                    if(lastHot.getScore() < score){
                        HotArticleVo hot = new HotArticleVo();
                        BeanUtils.copyProperties(apArticle,hot);
                        hot.setScore(score);
                        hotArticleVos.add(hot);
                        hotArticleVos.remove(lastHot);
                    }
                }else {
                    HotArticleVo hot = new HotArticleVo();
                    BeanUtils.copyProperties(apArticle,hot);
                    hot.setScore(score);
                    hotArticleVos.add(hot);
                }


            }

            //排序
            hotArticleVos = hotArticleVos.stream().sorted(Comparator.comparing(HotArticleVo::getScore).reversed()).collect(Collectors.toList());
            //存入redis
            cacheService.set(key,JSON.toJSONString(hotArticleVos));

        }
    }

    /**
     * 更新数据库的行为数量
     *
     * @param mess
     */
    private ApArticle updateArticle(ArticleVisitStreamMess mess) {
        ApArticle apArticle = getById(mess.getArticleId());
        apArticle.setViews((apArticle.getViews() == null ? 0 : apArticle.getViews()) + mess.getView());
        apArticle.setComment((apArticle.getComment() == null ? 0 : apArticle.getComment()) + mess.getComment());
        apArticle.setCollection((apArticle.getCollection() == null ? 0 : apArticle.getCollection()) + mess.getCollect());
        apArticle.setLikes((apArticle.getLikes() == null ? 0 : apArticle.getLikes()) + mess.getLike());
        updateById(apArticle);

        return apArticle;
    }

    /**
     * 计算文章的具体分值
     * @param apArticle
     * @return
     */
    private Integer computeScore(ApArticle apArticle) {

        Integer score = 0;
        if(apArticle.getViews() != null){
            score += apArticle.getViews();
        }

        if(apArticle.getLikes() != null){
            score += apArticle.getLikes() * ArticleConstants.HOT_ARTICLE_LIKE_WEIGHT;
        }

        if(apArticle.getComment() != null){
            score += apArticle.getComment() * ArticleConstants.HOT_ARTICLE_COMMENT_WEIGHT;
        }

        if(apArticle.getCollection() != null){
            score += apArticle.getCollection() * ArticleConstants.HOT_ARTICLE_COLLECTION_WEIGHT;
        }

        return score;
    }
}
